package com.jt;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.pojo.ItemDesc;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author dc
 * @Classname testJson
 * @Date 2020/2/18 10:28
 */
public class testJson {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Test
    public void test2Json() throws JsonProcessingException {
        //1.由对象转换为json
        ItemDesc itemDesc = new ItemDesc();
        itemDesc.setItemId(1000L).setItemDesc("json测试");
        String jsonStr = MAPPER.writeValueAsString(itemDesc);
        System.out.println(jsonStr);
        //2.由json转化为对象 反射
        ItemDesc obj = MAPPER.readValue(jsonStr, ItemDesc.class);
        System.out.println(obj);
    }

    @SuppressWarnings("unchecked")
    @Test
    public void list2Json() throws JsonProcessingException {
        //1.list集合转换为json
        ItemDesc itemDesc1 = new ItemDesc();
        itemDesc1.setItemId(1000L).setItemDesc("json测试");
        ItemDesc itemDesc2 = new ItemDesc();
        itemDesc2.setItemId(1001L).setItemDesc("json测试");
        List<ItemDesc> itemDescs=new ArrayList<>();
        itemDescs.add(itemDesc1);
        itemDescs.add(itemDesc2);
        String jsonStr = MAPPER.writeValueAsString(itemDescs);
        System.out.println(jsonStr);
        //2.将json转化为对象
        List<ItemDesc> list =MAPPER.readValue(jsonStr,itemDescs.getClass());
        System.out.println(list);
    }
}
